package com.lib.common.helper.sharehelper.share

import android.content.Context
import android.graphics.Bitmap
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelmsg.*
import com.lib.common.helper.sharehelper.AShareListener
import com.lib.common.helper.sharehelper.entity.ShareData
import com.lib.common.helper.sharehelper.entity.ShareType
import com.lib.framework.base.BaseActivity
import com.lib.framework.manager.thread.bgThreadRun
import com.lib.framework.manager.thread.mainThreadRun
import com.lib.framework.utils.BitmapUtil
import com.xiangwushuo.thirdparty.weixin.WeiXinHelper

/**
 * 微信好友分享
 *
 * @author keanbin
 */
open class WeiXinFriendShare(context: Context) : IShare {

    companion object {

        /**
         * 缩略图 尺寸
         */
        private const val THUMB_SIZE = 120
    }

    private var mContext = context.applicationContext

    override fun init() {
        WeiXinHelper.init(mContext)
    }

    override fun getShareType() = ShareType.WEI_XIN_FRIEND_SHARE

    override fun share(activity: BaseActivity, shareData: ShareData, l: AShareListener): Boolean {
        if (!WeiXinHelper.isInstallWeiXin()) {
            mainThreadRun {
                l.onShareFail("请先安装微信")
            }
            return false
        }

        bgThreadRun {
            val ret = WeiXinHelper.sendShare(shareDataToBaseReq(shareData), object : WeiXinHelper.OnShareCallback {
                override fun onShareSuccess() {
                    mainThreadRun {
                        l.onShareSuccess()
                    }
                }

                override fun onShareFail(msg: String) {
                    mainThreadRun {
                        l.onShareFail(msg)
                    }
                }

                override fun onShareCancel() {
                    mainThreadRun {
                        l.onShareCancel()
                    }
                }
            })

            if (!ret) {
                mainThreadRun {
                    l.onShareFail("分享失败")
                }
            }
        }

        return true
    }

    /**
     * ShareData 转换成 BaseReq
     */
    protected open fun shareDataToBaseReq(shareData: ShareData): BaseReq? {
        when (shareData.shareDataType) {
            ShareData.ShareDataType.TEXT -> {
                return createTextBaseReq(shareData)
            }

            ShareData.ShareDataType.IMAGE -> {
                return createImgBaseReq(shareData)
            }

            ShareData.ShareDataType.MUSIC -> {
                return createMusicBaseReq(shareData)
            }

            ShareData.ShareDataType.VIDEO -> {
                return createVideoBaseReq(shareData)
            }

            ShareData.ShareDataType.WEBPAGE -> {
                return createWebpageBaseReq(shareData)
            }
        }

        return null
    }

    /**
     * 创建 文本 BaseReq
     */
    private fun createTextBaseReq(shareData: ShareData): BaseReq? {
        val textObj = WXTextObject()
        textObj.text = shareData.title

        val msg = WXMediaMessage()
        msg.mediaObject = textObj
        msg.description = shareData.title

        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
        return req
    }

    /**
     * 创建 图片 BaseReq
     */
    private fun createImgBaseReq(shareData: ShareData): BaseReq? {
        val bmp = shareData.imgBmp
                ?: BitmapUtil.getBitmapFromUri(mContext.contentResolver, shareData.imgUri)
                ?: return null

        val imgObj = WXImageObject(bmp)

        val msg = WXMediaMessage()
        msg.mediaObject = imgObj

        val thumbBmp = createScaledBitmap(bmp)
        bmp.recycle()
        msg.thumbData = BitmapUtil.bmpToByteArray(thumbBmp, true)

        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
        return req
    }

    /**
     * 创建 音乐 BaseReq
     */
    private fun createMusicBaseReq(shareData: ShareData): BaseReq? {
        val music = WXMusicObject()
        music.musicUrl = shareData.url

        val msg = WXMediaMessage()
        msg.mediaObject = music
        msg.title = shareData.title
        msg.description = shareData.description

        val bmp = BitmapUtil.getBitmapFromUri(mContext.contentResolver, shareData.imgUri)
        bmp?.let {
            val thumbBmp = createScaledBitmap(bmp)
            bmp.recycle()
            msg.thumbData = BitmapUtil.bmpToByteArray(thumbBmp, true)
        }

        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
        return req
    }

    /**
     * 创建 视频 BaseReq
     */
    private fun createVideoBaseReq(shareData: ShareData): BaseReq? {
        val video = WXVideoObject()
        video.videoUrl = shareData.url

        val msg = WXMediaMessage()
        msg.mediaObject = video
        msg.title = shareData.title
        msg.description = shareData.description

        val bmp = BitmapUtil.getBitmapFromUri(mContext.contentResolver, shareData.imgUri)
        bmp?.let {
            val thumbBmp = createScaledBitmap(bmp)
            bmp.recycle()
            msg.thumbData = BitmapUtil.bmpToByteArray(thumbBmp, true)
        }

        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
        return req
    }

    /**
     * 创建 网页 BaseReq
     */
    private fun createWebpageBaseReq(shareData: ShareData): BaseReq? {
        val webpage = WXWebpageObject()
        webpage.webpageUrl = shareData.url

        val msg = WXMediaMessage()
        msg.mediaObject = webpage
        msg.title = shareData.title
        msg.description = shareData.description

        val bmp = BitmapUtil.getBitmapFromUri(mContext.contentResolver, shareData.imgUri)
        bmp?.let {
            val thumbBmp = createScaledBitmap(bmp)
            bmp.recycle()
            msg.thumbData = BitmapUtil.bmpToByteArray(thumbBmp, true)
        }

        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
        return req
    }

    private fun buildTransaction(type: String? = null): String {
        return if (type == null) System.currentTimeMillis().toString() else type + System.currentTimeMillis()
    }

    /**
     * 生成缩率图
     */
    private fun createScaledBitmap(bmp: Bitmap): Bitmap {
        val widthOrg = bmp.width
        val heightOrg = bmp.height

        if (widthOrg > heightOrg) {
            if (widthOrg <= THUMB_SIZE) return bmp

            val width = THUMB_SIZE
            val height = width * heightOrg / widthOrg
            return Bitmap.createScaledBitmap(bmp, width, height, true)
        } else {
            if (heightOrg <= THUMB_SIZE) return bmp

            val height = THUMB_SIZE
            val width = height * widthOrg / heightOrg

            return Bitmap.createScaledBitmap(bmp, width, height, true)
        }
    }
}